const fs = require('fs-extra');
const serve = require('koa-static');
const Koa = require('koa');
const router = require('koa-router')();
const app = new Koa();
const bodyParser = require('koa-bodyparser');

/**
 * 【GET】data/{{ 具体数据服务 }}
 * getIndexRumorList : 最新辟谣
 * getIndexRecommendList : 最新防护知识
 * getWikiList : 最新知识百科
 * getEntries : 诊疗信息
 * getListByCountryTypeService1 : 全国省份级患者分布数据
 * getListByCountryTypeService2 : 全球海外其他地区患者分布数据
 * getStatisticsService : 获取整体统计信息
 */
router.get('/data/:serviceName', async (ctx,next) => {
    try {
        let serviceName = ctx.params.serviceName;
        console.log(`service = ${serviceName}`);
        let data = await fs.readJSON('./resource/data.json');
        let content = data[serviceName];
        if(content){          
            ctx.response.body = content;
        }else{
            ctx.response.body = '没找到相关信息 Not Found'
        }
    } catch (error) {
        console.log(`${serviceName} `, error);   
    }
});

//【GET】获取指定省份的信息
router.get('/data/getAreaStat/:provice', async (ctx, next) =>{
    let provice = ctx.params.provice;
    console.log(ctx.params)
    let data = await fs.readJSON('./resource/data.json');
    let areaStat = data.getAreaStat;
    if(provice){
        let body = [];
        for(let i = 0; i<areaStat.length; i++){
            let area = areaStat[i];
            if(area.provinceName == provice || area.provinceShortName == provice){
                body.push(area);
                break;
            }
        }
        ctx.response.body = body;
    }else{
        ctx.response.body = areaStat;
    }

});

//【GET】 查询目标邮箱名是否在订阅列表
router.get('/mail/check/:mail', async (ctx, next) =>{
    let mail = ctx.params.mail || ''
    let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    let isEmail = reg.test(mail) ? true : false
    console.log('格式', isEmail) 
    if(!isEmail) {
        ctx.response.body = { error: '邮件格式不正确，拦截请求'}    
        return
    } 
    let checkResult = await checkMail( mail )  
    if( checkResult ){       
        ctx.response.body = { status:1 }
    }else{       
        ctx.response.body = { status:0 }
    }   
});
// 【GET】 新增邮箱名 tatus=>10(出现错误) status=>2(正常)
router.get('/mail/plus/:mail', async (ctx, next) =>{
    let mail = ctx.params.mail || ''
    let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    let isEmail = reg.test(mail) ? true : false
    let checkResult = await checkMail(mail) 
    console.log('格式', isEmail)     
    // 检查格式    
    if(!isEmail) {
        ctx.response.body = { error: '邮件格式不正确，拦截请求', status: 10 }    
        return
    }     
    // 去重
    if ( checkResult ){
        ctx.response.body = { warn: '邮箱名已存在，拦截请求', status: 10  }
        return
    }
    let fileData = await fs.readJSON('./resource/mail.json')
    let mailList = fileData.toList
    mailList.push( mail )
    let resultObj = {
        "toList": mailList
    }
    await fs.writeJSON('./resource/mail.json', resultObj ) //保存MAIL数据
    ctx.response.body = { data: '新增mail ok', status: 2 }
});

// 【GET】 删除邮箱名 status=>10(出现错误) status=>2(正常)
router.get('/mail/cut/:mail', async (ctx, next) =>{
    let mail = ctx.params.mail || ''
    let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    let isEmail = reg.test(mail) ? true : false
    let checkResult = await checkMail(mail) 
    console.log('格式', isEmail)     
    // 检查格式    
    if(!isEmail) {
        ctx.response.body = { error: '邮件格式不正确，拦截请求', status: 10 }    
        return
    }     
    // 不存在则跳过
    if ( !checkResult ){
        ctx.response.body = { warn: '邮箱名不存在，拦截请求', status: 10  }
        return
    }
    let fileData = await fs.readJSON('./resource/mail.json')
    let mailList = fileData.toList
    let index = mailList.findIndex( item => item === mail ) // 确定索引
    if(index>-1){
        mailList.splice(index, 1)
        let resultObj = { "toList": mailList }
        await fs.writeJSON('./resource/mail.json', resultObj )     //保存MAIL数据
        ctx.response.body = { data: '删除mail ok', status: 2 }
    }else{
        ctx.response.body = { data: '删除mail 失败 不存在邮箱/未知错误', status: 10 }
    }      
});

// 【允许跨域请求】路由中间件
app.use(async (ctx, next)=> {
    ctx.set('Access-Control-Allow-Origin', '*');
    // ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
      ctx.body = 200; 
    } else {
      await next();
    }
  });

app.use(bodyParser());
app.use(router.routes());

app.listen(3001);
console.log('app started at port 3001...');


// 判断邮件名是否在订阅列表
async function checkMail ( mail ) {
    let fileData = await fs.readJSON('./resource/mail.json')
    let mailList = fileData.toList
    if( mailList.indexOf(mail) > -1 ){
        console.log('Mail IN', mail)
        return true
    }else{
        console.log('Mail NONO', mail)
        return false
    }   
}